package com.zd.mock.huyisen;

import com.github.javafaker.Faker;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Locale;
import java.util.Random;
import java.math.BigDecimal;

public class OrderItemsDataGenerator {

    private static final String DB_URL = "jdbc:mysql://hadoop102:3306/zhengzhou_tourism_business?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    private static final Faker faker = new Faker(new Locale("zh-CN"));
    private static final Random random = new Random();

    public static void main(String[] args) {
        int count = 1000;
        generateOrderItems(count);
    }

    public static void generateOrderItems(int count) {
        String insertSql = "INSERT INTO order_items " +
                "(order_id, item_type, product_id, product_name, quantity, unit_price, total_price, start_date, end_date, status, create_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(insertSql)) {

            conn.setAutoCommit(false);

            for (int i = 1; i <= count; i++) {
                // 生成 order_id，模拟类似ORD202301011001格式
                String orderId = generateOrderId(i);

                // item_type: 1-门票 2-住宿 3-商品 4-路线
                int itemType = random.nextInt(4) + 1;

                // product_id 模拟产品ID，1~20随机
                int productId = random.nextInt(20) + 1;

                // 根据 itemType 生成对应产品名
                String productName = generateProductName(itemType);

                // 数量，1~5
                int quantity = random.nextInt(5) + 1;

                // 单价和总价
                double unitPrice = generateUnitPrice(itemType);
                double totalPrice = unitPrice * quantity;

                // 使用/入住日期，最近90天随机日期
                LocalDate startDate = randomLocalDateBetweenDays(90);

                // 结束日期仅住宿专用（item_type=2），入住日期基础上加1~5天
                LocalDate endDate = null;
                if (itemType == 2) {
                    endDate = startDate.plusDays(random.nextInt(5) + 1);
                }

                // 状态，0或1随机
                int status = random.nextBoolean() ? 1 : 0;

                // 创建时间，当前时间
                Timestamp createTime = Timestamp.valueOf(LocalDateTime.now());

                pstmt.setString(1, orderId);
                pstmt.setInt(2, itemType);
                pstmt.setInt(3, productId);
                pstmt.setString(4, productName);
                pstmt.setInt(5, quantity);
                pstmt.setBigDecimal(6, BigDecimal.valueOf(unitPrice));
                pstmt.setBigDecimal(7, BigDecimal.valueOf(totalPrice));

                if (startDate != null) {
                    pstmt.setDate(8, java.sql.Date.valueOf(startDate));
                } else {
                    pstmt.setNull(8, Types.DATE);
                }

                if (endDate != null) {
                    pstmt.setDate(9, java.sql.Date.valueOf(endDate));
                } else {
                    pstmt.setNull(9, Types.DATE);
                }

                pstmt.setInt(10, status);
                pstmt.setTimestamp(11, createTime);

                pstmt.addBatch();

                if (i % BATCH_SIZE == 0) {
                    pstmt.executeBatch();
                }
            }

            pstmt.executeBatch();
            conn.commit();
            System.out.println("成功插入 " + count + " 条 order_items 数据");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String generateOrderId(int index) {
        LocalDateTime now = LocalDateTime.now();
        // 生成格式如 ORD202306280001
        return String.format("ORD%04d%02d%02d%04d", now.getYear(), now.getMonthValue(), now.getDayOfMonth(), index);
    }

    private static String generateProductName(int itemType) {
        switch (itemType) {
            case 1:
                return faker.book().title() + "门票"; // 门票产品名
            case 2:
                return faker.company().name() + "酒店"; // 住宿产品名
            case 3:
                return faker.commerce().productName(); // 商品名
            case 4:
                return faker.address().cityName() + "旅游路线"; // 路线名
            default:
                return "产品";
        }
    }

    private static double generateUnitPrice(int itemType) {
        switch (itemType) {
            case 1: return 100 + random.nextInt(200); // 门票
            case 2: return 300 + random.nextInt(500); // 住宿
            case 3: return 50 + random.nextInt(300);  // 商品
            case 4: return 200 + random.nextInt(400); // 路线
            default: return 100;
        }
    }

    private static LocalDate randomLocalDateBetweenDays(int pastDays) {
        long minDay = LocalDate.now().minusDays(pastDays).toEpochDay();
        long maxDay = LocalDate.now().toEpochDay();
        long randomDay = minDay + (long) (Math.random() * (maxDay - minDay + 1));
        return LocalDate.ofEpochDay(randomDay);
    }
}
